package com.itheima.project.job;

import com.itheima.project.basic.ResponseWrap;
import com.itheima.project.constant.trade.TradingConstant;
import com.itheima.project.face.OrderFace;
import com.itheima.project.feign.BasicPayFeign;
import com.itheima.project.feign.TradingFeign;
import com.itheima.project.utils.EmptyUtil;
import com.itheima.project.vo.trade.RefundRecordVo;
import com.itheima.project.vo.trade.TradingVo;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description：NativePay付款结果同步
 */
@Component
public class NativePayHandlerJob {


    @Autowired
    TradingFeign tradingFeign;

    @Autowired
    BasicPayFeign basicPayFeign;

    @Autowired
    OrderFace orderFace;

    /***
     * @description NativePay付款结果同步
     * @param param
     * @return
     */
    @XxlJob(value = "nativePayHandlerJob")
    @GlobalTransactional
    public ReturnT<String> execute(String param) {
        //查询所有支付中的订单
        ResponseWrap<List<TradingVo>> responseWrap = tradingFeign.findTradingByTradingState(TradingConstant.FKZ);
        List<TradingVo> tradingVoList = responseWrap.getDatas();
        if (!EmptyUtil.isNullOrEmpty(tradingVoList)) {
            for (TradingVo tradingVo : tradingVoList) {
                this.synchTradingState(tradingVo);
            }
        }
        ReturnT.SUCCESS.setMsg("执行-支付同步-成功");
        return ReturnT.SUCCESS;
    }
    public void synchTradingState(TradingVo tradingVo){
        //交易单状态查询
        ResponseWrap<TradingVo> responseWrap = basicPayFeign.queryTrading(tradingVo);
        TradingVo tradingVoResult = responseWrap.getDatas();
        //订单状态同步交易单状态
        if (!EmptyUtil.isNullOrEmpty(tradingVoResult)){
            Long productOrderNo = tradingVoResult.getProductOrderNo();
            String tradingState = tradingVoResult.getTradingState();
            orderFace.synchTradingState(productOrderNo,tradingState);
        }
    }

    @XxlJob(value = "nativePayQueryRefundJob")
    public ReturnT<String> executeQueryRefund(String param) {
        //查询所有支付中的订单
        ResponseWrap<List<RefundRecordVo>> responseWrap = tradingFeign.findReFundRecordByRefundStatus(TradingConstant.REFUND_STATUS_SENDING);
        List<RefundRecordVo> refundRecordVos = responseWrap.getDatas();
        if (!EmptyUtil.isNullOrEmpty(refundRecordVos)) {
            for (RefundRecordVo refundRecordVo : refundRecordVos) {
               basicPayFeign.queryRefundTrading(refundRecordVo);
            }
        }

        ReturnT.SUCCESS.setMsg("执行-退款同步-成功");
        return ReturnT.SUCCESS;

    }


}
